<template>
	<view class="login-container">
		<view class="logo-box">
			<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
			<text class="title">棋牌室预约系统</text>
		</view>
		
		<view class="form-box">
			<!-- 登录方式切换选项卡 -->
			<view class="login-tabs">
				<view 
					:class="['tab-item', loginType === 'email' ? 'active' : '']" 
					@click="loginType = 'email'"
				>
					邮箱登录
				</view>
				<view 
					:class="['tab-item', loginType === 'wechat' ? 'active' : '']" 
					@click="loginType = 'wechat'"
				>
					微信登录
				</view>
			</view>
			
			<!-- 邮箱登录表单 -->
			<view v-if="loginType === 'email'" class="login-form">
				<view class="input-group">
					<text class="label">邮箱</text>
					<input class="input" type="text" v-model="email" placeholder="请输入邮箱地址" />
				</view>
				
				<view class="input-group">
					<text class="label">验证码</text>
					<input class="input" type="text" v-model="code" placeholder="请输入验证码" maxlength="6" />
					<view :class="['code-btn', sendingCode ? 'disabled' : '']" @click="sendVerificationCode">
						{{ codeBtnText }}
					</view>
				</view>
				
				<button class="login-btn" @click="handleEmailLogin">登录</button>
			</view>
			
			<!-- 微信登录 -->
			<view v-else class="wechat-login">
				<view class="wechat-tip">
					<text>点击下方按钮，快速登录</text>
				</view>
				
				<!-- 微信环境下显示授权按钮 -->
				<!-- #ifdef MP-WEIXIN -->
				<button class="wechat-btn" open-type="getUserInfo" @getuserinfo="handleWxLogin">
					<image src="/static/icon/wechat.png" class="wechat-icon"></image>
					微信一键登录
				</button>
				<!-- #endif -->
				
				<!-- 非微信环境下显示普通按钮 -->
				<!-- #ifndef MP-WEIXIN -->
				<button class="wechat-btn" @click="handleWxLogin">
					<image src="/static/icon/wechat.png" class="wechat-icon"></image>
					微信一键登录
				</button>
				<!-- #endif -->
				
				<view class="wechat-privacy">
					登录即代表您已同意<text class="link">《用户协议》</text>和<text class="link">《隐私政策》</text>
				</view>
			</view>
			
			<view class="register-link">
				还没有账号？<text class="link" @click="goToRegister">立即注册</text>
			</view>
		</view>
	</view>
</template>

<script>
import request, { BASE_URL } from '@/utils/request.js';
import { setToken, setUserInfo } from '@/utils/auth.js';

export default {
	data() {
		return {
			loginType: 'email', // 默认邮箱登录
			email: '',
			code: '',
			sendingCode: false,
			countdown: 60,
			timer: null
		}
	},
	computed: {
		codeBtnText() {
			return this.sendingCode ? `${this.countdown}秒` : '获取验证码';
		}
	},
	methods: {
		/**
		 * 发送验证码
		 */
		async sendVerificationCode() {
			// 验证邮箱格式
			if (!this.validateEmail(this.email)) {
				uni.showToast({
					title: '请输入正确的邮箱地址',
					icon: 'none'
				});
				return;
			}
			
			// 防止重复发送
			if (this.sendingCode) {
				return;
			}
			
			try {
				this.sendingCode = true;
				
				// 调用发送验证码接口
				const res = await request.post('/api/mobile/user/email/verify', {
					email: this.email,
					type: 'login'
				});
				
				uni.showToast({
					title: '验证码已发送',
					icon: 'success'
				});
				
				// 开始倒计时
				this.startCountdown();
			} catch (error) {
				this.sendingCode = false;
				uni.showToast({
					title: '验证码发送失败',
					icon: 'none'
				});
			}
		},
		
		/**
		 * 验证码倒计时
		 */
		startCountdown() {
			this.countdown = 60;
			this.timer = setInterval(() => {
				if (this.countdown > 0) {
					this.countdown--;
				} else {
					this.sendingCode = false;
					clearInterval(this.timer);
				}
			}, 1000);
		},
		
		/**
		 * 处理邮箱登录
		 */
		async handleEmailLogin() {
			// 表单校验
			if (!this.validateEmail(this.email)) {
				uni.showToast({
					title: '请输入正确的邮箱地址',
					icon: 'none'
				});
				return;
			}
			
			if (!this.code || this.code.length !== 6) {
				uni.showToast({
					title: '请输入6位验证码',
					icon: 'none'
				});
				return;
			}
			
			try {
				uni.showLoading({
					title: '登录中...'
				});
				
				// 调用登录接口
				const res = await request.post('/api/mobile/user/login', {
					email: this.email,
					code: this.code
				});
				
				// 保存登录信息
				setToken(res.data.token);
				setUserInfo(res.data.userInfo);
				
				uni.hideLoading();
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});
				
				// 邮箱登录成功后跳转到首页
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}, 1500);
			} catch (error) {
				uni.hideLoading();
			}
		},
		
		/**
		 * 处理微信登录
		 */
		handleWxLogin(e) {
			// 微信小程序环境
			// #ifdef MP-WEIXIN
			if (e.detail.errMsg === 'getUserInfo:ok') {
				// 清除可能存在的旧数据
				uni.removeStorageSync('token');
				uni.removeStorageSync('userInfo');
				
				uni.showLoading({
					title: '登录中...'
				});
				
				// 设置请求超时
				const loginTimeout = setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '登录超时，请重试',
						icon: 'none',
						duration: 2000
					});
				}, 15000); // 15秒超时
				
				// 获取登录凭证(code)
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						// 打印登录code，便于调试
						console.log('获取到微信code:', loginRes.code);
						
						// 获取用户信息
						const userInfo = e.detail.userInfo;
						console.log('获取到用户信息:', userInfo);
						
						// 请求完整URL日志
						const loginUrl = '/api/mobile/user/wx/login';
						console.log('请求微信登录API:', BASE_URL + loginUrl);
						
						// 将code和用户信息发送到后端
						request.post(loginUrl, {
							wxCode: loginRes.code,
							userInfo: userInfo
						}).then(res => {
							clearTimeout(loginTimeout); // 清除超时
							console.log('微信登录成功:', res);
							
							// 保存登录信息
							setToken(res.data.token);
							setUserInfo(res.data.userInfo);
							
							uni.hideLoading();
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});
							
							// 微信登录成功后跳转到首页
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}, 1500);
						}).catch(err => {
							clearTimeout(loginTimeout); // 清除超时
							console.error('微信登录请求失败:', err);
							uni.hideLoading();
							uni.showToast({
								title: '登录失败，请稍后重试',
								icon: 'none',
								duration: 2000
							});
						});
					},
					fail: (err) => {
						clearTimeout(loginTimeout); // 清除超时
						console.error('获取微信code失败:', err);
						uni.hideLoading();
						uni.showToast({
							title: '微信登录失败',
							icon: 'none'
						});
					}
				});
			} else {
				console.log('用户拒绝了微信授权:', e.detail.errMsg);
				uni.showToast({
					title: '您已取消登录授权',
					icon: 'none'
				});
			}
			// #endif
			
			// App环境
			// #ifdef APP-PLUS
			uni.login({
				provider: 'weixin',
				success: (loginRes) => {
					// 将授权结果发送到后端
					const authResult = loginRes.authResult;
					request.post('/api/mobile/user/wx/login', {
						wxAuthResult: authResult
					}).then(res => {
						// 保存登录信息
						setToken(res.data.token);
						setUserInfo(res.data.userInfo);
						
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						
						// 微信登录成功后跳转到首页
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}, 1500);
					}).catch(err => {
						uni.showToast({
							title: '登录失败',
							icon: 'none'
						});
					});
				},
				fail: () => {
					uni.showToast({
						title: '微信登录失败',
						icon: 'none'
					});
				}
			});
			// #endif
			
			// H5和其他环境
			// #ifdef H5 || MP-ALIPAY || MP-QQ || MP-BAIDU || MP-TOUTIAO
			uni.showToast({
				title: '请在微信环境中使用该功能',
				icon: 'none'
			});
			// #endif
		},
		
		/**
		 * 跳转到注册页面
		 */
		goToRegister() {
			uni.navigateTo({
				url: '/pages/register/register'
			});
		},
		
		/**
		 * 验证邮箱格式
		 */
		validateEmail(email) {
			const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
			return reg.test(email);
		}
	},
	onUnload() {
		// 页面卸载时清除定时器
		if (this.timer) {
			clearInterval(this.timer);
		}
	}
}
</script>

<style lang="scss">
.login-container {
	min-height: 100vh;
	padding: 50rpx;
	background-color: #f8f8f8;
	display: flex;
	flex-direction: column;
	
	.logo-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 60rpx;
		margin-bottom: 80rpx;
		
		.logo {
			width: 180rpx;
			height: 180rpx;
		}
		
		.title {
			margin-top: 30rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.form-box {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		box-shadow: 0 0 20rpx rgba(0,0,0,0.05);
	}
	
	.login-tabs {
		display: flex;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 40rpx;
		
		.tab-item {
			flex: 1;
			text-align: center;
			font-size: 32rpx;
			color: #666;
			padding: 20rpx 0;
			position: relative;
			
			&.active {
				color: #7FB992;
				font-weight: bold;
				
				&:after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 60rpx;
					height: 4rpx;
					background-color: #7FB992;
				}
			}
		}
	}
	
	.login-form {
		.input-group {
			position: relative;
			margin-bottom: 40rpx;
			
			.label {
				display: block;
				font-size: 28rpx;
				color: #666;
				margin-bottom: 15rpx;
			}
			
			.input {
				width: 100%;
				height: 90rpx;
				background-color: #f5f5f5;
				border-radius: 10rpx;
				padding: 0 20rpx;
				font-size: 30rpx;
				color: #333;
			}
			
			.code-btn {
				position: absolute;
				right: 20rpx;
				bottom: 25rpx;
				font-size: 28rpx;
				color: #7FB992;
				
				&.disabled {
					color: #999;
				}
			}
		}
	}
	
	.login-btn, .wechat-btn {
		width: 100%;
		height: 90rpx;
		border-radius: 10rpx;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 60rpx;
		margin-bottom: 40rpx;
	}
	
	.login-btn {
		background-color: #7FB992;
		color: #fff;
	}
	
	.wechat-login {
		.wechat-tip {
			text-align: center;
			font-size: 28rpx;
			color: #666;
			margin: 30rpx 0;
		}
		
		.wechat-btn {
			background-color: #07c160;
			color: #fff;
			
			.wechat-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}
		}
		
		.wechat-privacy {
			text-align: center;
			font-size: 24rpx;
			color: #999;
			margin-bottom: 20rpx;
			
			.link {
				color: #7FB992;
			}
		}
	}
	
	.register-link {
		text-align: center;
		font-size: 28rpx;
		color: #666;
		
		.link {
			color: #7FB992;
		}
	}
}
</style> 